package kepu_res

import (
	"github.com/jinzhu/gorm"
	"strconv"
	"strings"
)

type Res struct {
	Title string `json:"title"`
	Id    int    `json:"id"`
	Uuid  string `json:"uuid"`
	Url   string `json:"url"`
}

func (m *Res) TableName() string {
	return "resource"
}

func updateUrl(p *Res, url string) {
	p.Url = url
}
func Get(uuids []string) (articles []Res, err error) {
	err = db.Table("resource as r").
		Joins("left join resource_relation as rr  on rr.uuid = r.uuid").
		Joins("left join resource_image as ri on ri.id = rr.res_id").
		Select("r.id,r.title,r.uuid,ri.url").
		Where("r.uuid in (?) ", uuids).
		Order("r.id desc").Find(&articles).Error

	if err != nil && err != gorm.ErrRecordNotFound {
		return articles, err
	}
	str, err := GetDoman()
	for key, article := range articles {
		for dourl, domain := range str {
			article.Url = strings.Replace(article.Url, dourl, domain, 1)
			updateUrl(&articles[key], article.Url)
		}

	}

	return articles, nil
}

type Domain struct {
	Id     int    `json:"id"`
	Domain string `json:"domain"`
	Idurl  string `json:"idurl"`
}

func GetDoman() (str map[string]string, err error) {
	var Domains []Domain
	err = db.Table("resource_domain").Select("id,domain").Where("domain_type = 1").Find(&Domains).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return str, err
	}
	str = make(map[string]string)

	for _, domain := range Domains {
		domain.Idurl = "↑" + strconv.Itoa(domain.Id) + "↑"
		str[domain.Idurl] = domain.Domain
	}
	return str, err

}

func GetArticle(page int, size int) (articles []Res, count int, err error) {
	offest := (page - 1) * size
	err = db.Table("resource as r").
		Joins("left join resource_relation as rr  on rr.uuid = r.uuid").
		Joins("left join resource_image as ri on ri.id = rr.res_id").
		Select("r.id,r.title,r.uuid,ri.url").
		//Where("r.uuid in (?) ", uuids).
		Order("r.id desc").Offset(offest).Limit(size).Find(&articles).Error

	if err != nil && err != gorm.ErrRecordNotFound {
		return articles, 0, err
	}
	db.Table("resource").Select("id").Count(&count)

	return articles, count, nil
}
